import logging
from ol_user import OnlineUser, OnlineUserList
from poker.poker_base import PokerBase
from game_ import Game
from google.appengine.ext.webapp import RequestHandler

class CommandLineResource(RequestHandler):
    users = OnlineUserList()
    n = 0

    def __init__(self):
        self.poker = PokerBase()

    def post(self):
        logging.critical(self.request.arguments())
        cmd = str(self.request.get('cmd'))
        args = self.request.get('args').split(' ')
        args = [str(i) for i in args]
        return self.response.out.write(self.handler(cmd, args))

    def handler(self, cmd, args):
        logging.critical('%s,,,%s' % (cmd, args))
        if cmd == 'JOIN':
            u_id = self.users.genId()
            name = args[0]
            newUser = OnlineUser(u_id, name)
            self.users.addUser(u_id, newUser)

            rtn_cmd = 'ACK_JOIN'
            rtn_args = [u_id, name]
            for user in self.users.getAll():
                if user.id != u_id:
                    newUser.addCmd('ACK_JOIN_B', [user.id, user.name])
            self.users.broadcastCmd('ACK_JOIN_B', rtn_args, u_id)

        elif cmd == 'READY':
            u_id = args[0]
            self.users.setUserState(u_id, 100) # user_state.READY
            rtn_cmd = 'ACK_READY'
            rtn_args = [u_id]
            self.users.broadcastCmd('ACK_READY_B', rtn_args, u_id)

            if self.users.readyUser == 3:
                Game().start()

        elif cmd == 'REQ_CARD':
            u_id = args[0]
            card = self.poker.getOneCard()
            self.users.addCard(u_id, card)

            rtn_cmd = 'DISPATCH_CARD'
            rtn_args = [u_id, card]
            self.users.broadcastCmd('DISPATCH_CARD_B', [u_id], u_id)

        elif cmd == '':
            rtn_cmd = ''
            rtn_args = ''

        else:
            rtn_cmd = cmd
            rtn_args = args

        rtn = [{'cmd': rtn_cmd, 'args': rtn_args}]
        logging.critical('%s' % rtn)
        return str(rtn)


